package cn.itcast.nems.common.captcha;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public class SmsCaptchaSendUtil {
    // 短信中心接口地址
    public static String SMS_CENTER_URL;
    // 短信中心密钥
    public static String SMS_CENTER_PRIVATE_KEY;
    // 短信中心短信模版ID
    public static String SMS_CENTER_TEMPLATEID;	
    
    @Value("${SMS_CENTER.URL:http://sms-center.boxuegu.com/smsCenterNew/v2}")
	public void setSmsCenterUrl(String smsCenterUrl) {
        SMS_CENTER_URL = smsCenterUrl;
    }

    @Value("${SMS_CENTER.PRIVATE_KEY:e9ee590ab082b65b}")
    public void setSmsCenterPrivateKey(String smsCenterPrivateKey) {
        SMS_CENTER_PRIVATE_KEY = smsCenterPrivateKey;
    }

    @Value("${SMS_CENTER.TEMPLATE_ID:SMS20180129ZkmFbxrU}")
    public void setSmsCenterTemplateId(String smsCenterTemplateId) {
        SMS_CENTER_TEMPLATEID = smsCenterTemplateId;
    }

    public static void sendCaptchaCode(String mobile, String code) {

		// 1.参数列表
		Long timestamp = System.currentTimeMillis() / 1000L;
		
		// 签名加密：md5(privatekey_mobile_templateId_timestamp)
		String sign = DigestUtils.md5DigestAsHex((SMS_CENTER_PRIVATE_KEY + "_" + mobile + "_" + SMS_CENTER_TEMPLATEID + "_" + timestamp).getBytes()).toUpperCase();
		
		String smsParams = "[\""+ code +"\"]";
		
		// 2.封装参数
		MultiValueMap<String, Object> map= new LinkedMultiValueMap<>();
		map.add("mobile", mobile);
		map.add("params", smsParams);
		map.add("sign", sign);
		map.add("templateid", SMS_CENTER_TEMPLATEID);
		map.add("timestamp", timestamp);
		
		HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);		
		String msg = restTemplate.postForObject(SMS_CENTER_URL, request, String.class);
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			log.debug("短信发送 - 发送时间：{}，手机号：{}，验证码：{}，发送接口结果消息：{}" , new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) , mobile , code, msg);
			
			Map<String, ?> map2 = mapper.readValue(msg, Map.class);
			
			Integer status = map2!=null ? (Integer) map2.get("status") : HttpStatus.BAD_REQUEST.value();
			if (!status.equals(HttpStatus.OK.value())) {
				throw new SMSSendException(map2 != null ? (String) map2.get("message") : "");
			}
		} catch (Exception e) {
			log.error("验证码短信发送失败！错误：{}", e.getMessage());
		}
	}
}
